package com.hb.gp.util.command;

import java.util.List;

import com.hb.gp.util.MsgGenUtil;
import com.hb.gp.util.SetParam;
import com.hb.gp.util.tools.DES;
import com.hb.gp.util.tools.GP_GetMac;

public class APDU_ExternalAuth {
	public static String authention(String scp, String securityLevel,
			String initUpdateResponse, String random, List<String> sessionKeys)
			throws Exception {
		if (initUpdateResponse.length() < 56) {
			throw new Exception("data length wrong");
		}
		String pbCardChallenge = initUpdateResponse.substring(24, 40);
		String pbCardCryto = initUpdateResponse.substring(40, 56);
		StringBuffer buf = new StringBuffer();
		String pbTermChallenge = random;
		String src = null;
		String pbCardKeyEncSk = sessionKeys.get(0);
		String pbCardKeyMacSk = sessionKeys.get(1);
//		String pbCardKeyDekSk = sessionKeys.get(2);
		if (pbCardKeyEncSk == null || pbCardKeyEncSk.equals("")) {
			throw new Exception("sessionEncKey is null ");
		}
		if (pbCardKeyMacSk == null || pbCardKeyMacSk.equals("")) {
			throw new Exception("sessionEncKeyMacKey is null");
		}
		src = pbTermChallenge + pbCardChallenge + "8000000000000000";
		String iv = SetParam.GP_DEC_ICV;
		String res = "";
		// 软
		res = DES.encryptTDS_CBC(MsgGenUtil.BCD2Bytes(pbCardKeyEncSk),
				MsgGenUtil.BCD2Bytes(src));
		res = res.substring(32);
		if (!res.equalsIgnoreCase(pbCardCryto)) {
			throw new Exception("verify cardcryto fail!!!");
		}
		src = pbCardChallenge + pbTermChallenge + "8000000000000000";
		// 软
		res = DES.encryptTDS_CBC(MsgGenUtil.BCD2Bytes(pbCardKeyEncSk),
				MsgGenUtil.BCD2Bytes(src));
		buf.append("8482" + securityLevel + "0010");
		buf.append(res.substring(32));
		String macIcv = "";
		// macIcv = GP_GetMac.getIMac(buf.toString(), pbCardKeyMacSk, iv,
		// false);//
		// buf.append(macIcv);
		if (scp.equals("01")) {
			macIcv = DES.encryptTDS_CBC(MsgGenUtil.BCD2Bytes(pbCardKeyMacSk),
					MsgGenUtil.BCD2Bytes(buf.toString() + "800000"));//
			macIcv = macIcv.substring(16);
			buf.append(macIcv);
		}
		if (scp.equals("02")) {
			// System.out.println("mackey:"+pbCardKeyMacSk);
			macIcv = GP_GetMac.getIMac(buf.toString(), pbCardKeyMacSk, iv,
					false);//
			buf.append(macIcv);
		}
		return buf.toString();
	}

}
